package com.hmall.item.web;

import cn.hutool.json.JSONUtil;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.dto.Restore;
import com.hmall.common.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 分页查询商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> pageDTO( Integer page, Integer size){
        PageDTO<Item> pageDTO = itemService.page(page, size);
        return pageDTO;
    }

    /**
     * 启用禁用
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void isEnable(@PathVariable Long id, @PathVariable Integer status){
        itemService.isEnable(id, status);
    }


    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void save(@RequestBody Item item){
        item.setCreateTime(LocalDateTime.now());
        item.setUpdateTime(LocalDateTime.now());
        itemService.save(item);
    }

    /**
     * 修改商品
     * @param item
     */
    @PutMapping
    public void updateById(@RequestBody Item item){
        item.setUpdateTime(LocalDateTime.now());
        itemService.updateById(item);

        rabbitTemplate.convertAndSend("preheat.exchange", "preheat.all", "删除redis");
        itemService.preheatItems();
    }


    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Long id){
        itemService.removeById(id);

        rabbitTemplate.convertAndSend("preheat.exchange", "preheat.all", "删除redis");
        itemService.preheatItems();
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        return itemService.getById(id);
    }

    /**
     * 重回库存
     * @param jsonStr
     */
    @PostMapping("/restore")
    public void restore(String jsonStr){
        List<Restore> restore = JSONUtil.toList(jsonStr, Restore.class);
        itemService.restore(restore);
    }

}
